package com.magicborrow.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class PhotoUtil {

    /**
     * 图片质量压缩
     */
    private static final int quality = 90;

    /**
     * 创建文件
     */
    @SuppressLint("SimpleDateFormat")
    public static File newPhotoFile(String otherStamp) {
        File dir = null;
        try {
            dir = new File(FileUtil.getAppPath(), "Photo");
        } catch (Exception e) {
            Log.e("创建相册文件夹失败", e.getMessage());
        }
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String fileName = "Photo" + timeStamp + (otherStamp == null ? "" : "" + otherStamp + "") + ".jpg";
        File image = new File(dir, fileName);
        return image;
    }

    public static File newPhotoFile(String path, String name) {
        File dir = null;
        try {
            dir = new File(FileUtil.getAppPath(), path);
        } catch (Exception e) {
            Log.e("创建相册文件夹失败", e.getMessage());
        }
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File image = new File(dir, name + ".jpg");
        return image;
    }


    /**
     * 拍照Intent
     */
    public static File takePhotoIntent(Activity ac, int resultCode) {
        File file = newPhotoFile(null);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        ac.startActivityForResult(intent, resultCode);
        return file;
    }

    /**
     * 选择照片Intent
     */
    public static File choosePhotoIntent(Activity ac, int resultCode) {
        File file = newPhotoFile(null);
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        ac.startActivityForResult(intent, resultCode);
        return file;
    }


    /**
     * 剪切图标Intent
     *
     * @param activity    调用剪切功能的Activity
     * @param uri         待剪切的文件Uri
     * @param requestCode 请求码
     * @return iconFile 剪切后的图标文件
     * @author XieWenjun
     */
    public static void cropPhotoIntent(Activity activity, Uri uri, int requestCode,Uri newUri,int outputX,int outputY) {


        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        intent.putExtra("output", newUri);
        // intent.putExtra("MyUriKey", newUri.toString());
        intent.putExtra("outputX", 800);
        intent.putExtra("outputY", 800);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        intent.putExtra("noFaceDetection", true);

        activity.startActivityForResult(intent, requestCode);
        //return file;
    }


    /**
     * 修改图片(压缩比例+压缩质量)
     */
    private static synchronized void fixPhoto(Context context, String filePath, String finalFilePath, int quality,
                                              PhotoFixCallbackListener fixCallbackListener) {
        int reqHeight = 600;
        int reqWidth = 600;

        Bitmap bitmap;
        BitmapFactory.Options options;
        int degree;
        int height;
        int width;


        // 旋转角度
        degree = ImageUtil.readPhotoDegree(filePath);

        // 图片宽高
        options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        height = options.outHeight;
        width = options.outWidth;
        if (degree == 90 || degree == 270) {
            height = options.outWidth;
            width = options.outHeight;
        } else {
            height = options.outHeight;
            width = options.outWidth;
        }

        // 计算压缩比例
        options.inSampleSize = ImageUtil.calculateZoomSize(width, height, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        bitmap = BitmapFactory.decodeFile(filePath, options);

        // 旋转图片
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);

        // 保存到File
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(new FileOutputStream(finalFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, os);

        if (fixCallbackListener != null) {
            fixCallbackListener.onFixed(finalFilePath);
        }

        // 回收
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
            System.gc();
        }
    }

    /**
     * 拍照后的处理
     *
     * @param filePath 需要处理的文件路径,同时为处理后的文件路径(拍照出入的文件，所以处理之后也保存在拍照文件中)
     * @param
     */
    public static void fixPhoto(Context context, String filePath, PhotoFixCallbackListener fixCallbackListener) {
        fixPhoto(context, filePath, filePath, quality, fixCallbackListener);
    }

    /**
     * 选择图片后的处理
     *
     * @param context
     * @param uri     需要处理的文件Uri()
     *                保存处理后的文件路径 (选择图片不需要输入，得到的是Uri,所以需要一个新文件，保存处理后的图片)
     */
    public static void fixPhoto(Context context, Uri uri, PhotoFixCallbackListener fixCallbackListener) {
        fixPhoto(context, ImageUtil.getFilePath4Uri(context, uri), PhotoUtil.newPhotoFile(null).getAbsolutePath(), quality, fixCallbackListener);
    }

    /**
     * 多图选择后的批量处理
     *
     * @param context
     * @param files
     * @param fixCallbackListener
     */
    public static void fixPhotoList(final Context context, final ArrayList<String> files,
                                    final PhotoListFixCallbackListener fixCallbackListener) {
        // 用于保存
        final ArrayList<String> results = new ArrayList<String>();
        long time = System.currentTimeMillis();
        for (int i = 0; i < files.size(); i++) {
            results.add(FileUtil.newFile("Photo", "Photo" + time + "m" + i + ".jpg").getAbsolutePath());
        }

        // 顺序处理
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < files.size(); i++) {
                    fixPhoto(context, files.get(i), results.get(i), quality, null);
                }
                fixCallbackListener.onFixed(results);
            }
        }).start();
    }

    public interface PhotoFixCallbackListener {
        public void onFixed(String filePath);
    }

    public interface PhotoListFixCallbackListener {
        public void onFixed(ArrayList<String> filePaths);
    }


    public static String saveBitmap2SD(String sharePhotoName, Bitmap viewBitmap) {
        File file = newPhotoFile("Image", sharePhotoName);
        /*try {
            file.createNewFile();
		} catch (IOException e) {
			Log.e("在保存图片时出错：" + e.toString());
		}*/
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            viewBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);
        } catch (FileNotFoundException e) {
            Log.e("FileNotFoundException", e.getMessage());
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Log.e("IOException", e.getMessage());
            }

            if (viewBitmap != null && !viewBitmap.isRecycled()) {
                viewBitmap.recycle();
                viewBitmap = null;
                System.gc();
            }
        }

        return file.getAbsolutePath();
    }

}
